<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <!--    <meta charset="UTF-8">-->
    <!--    <title>产品菜单1</title>-->
    <!--    <link th:href="@{login/css/bootstrap1.css}" rel="stylesheet"/>-->

    <!--    <script th:src="@{login/js/bootstrap1.js}"></script>-->
    <!--    <script th:src="@{/login/js/jquery.js}"></script>-->
    <!--添加 CSRF 支持-->
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>

    <myhead th:replace="basic/layout :: head('后台管理页面1')"></myhead>
    <link th:href="@{/login/css/productTab.css}" rel="stylesheet"/>
</head>
<body>
<!--删除页面ajax法,后台主页面-->
<div class="container">
    <div th:replace="~{basic/layout :: topNav('back', ${currentUser})}"></div>
    <div class="row" style="width: 100%;margin: -10px 0;">
        <div th:replace="basic/layout :: menu"></div>
        <div style="position: relative;" class="col-10">
            <div id="liveAlertPlaceholder" style="position:fixed;top:38%;right:46%;"></div>
            <h3 class="card-title" style="margin-bottom: 10px">商品列表</h3>
            <a href="/admin/productTabList1" class="btn btn-primary insert btn-sm">新增商品</a>
            <table class="table table-hover w-100">
                <thead class="table-light">
                <tr>
                    <th>序号</th>
                    <th>图片</th>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>库存数量</th>
                    <th>分类</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="product:${products}">
                    <td>
                        <span class="num"></span>
                    </td>
                    <td>
                        <img th:src="${product.imageUrl}" class="card-img-top productImg" th:alt="${product.name}">
                    </td>
                    <td th:text="${product.name}"></td>
                    <td th:text="${product.price}"></td>
                    <td th:text="${product.stock}"></td>
                    <td>
                        <span class="badge text-bg-secondary productSpan" th:text="${product.category}"></span>
                    </td>
                    <td>
                        <span class="badge text-bg-success productSpan" th:if="${product.status} ==1">正常</span>
                        <span class="badge text-bg-danger productSpan" th:if="${product.status} ==0">下架</span>
                    </td>
                    <td>
                        <a th:href="@{/admin/productTabList1(id=${product.id})}" class="btn btn-primary btn-sm">修改</a>
<!--a th:href="@{/productTabList1(id=${product.id})}" 用于生成一个带参数的 跳转链接，传递参数，名为 id，值为 ${product.id}，跳转到 /productTabList1?id=xxx-->
<!--            GET 请求参数传递，id也会作为参数传回到后端-->
                        <button type="button" class="btn btn-danger" th:data-id="${product.id}"
                                onclick="showModal(this.dataset.id)">
                            删除
                        </button>
                    </td>
                </tr>
                </tbody>
                <script>
                    //序号的自动编号
                    document.querySelectorAll('.num').forEach((span, index) => {
                        span.textContent = index + 1;
                    });
                </script>
            </table>
        </div>
    </div>


    <!--模态框-->
    <div class="modal" tabindex="-1" id="deleteModal">
        <div class="modal-dialog">
            <div class="modal-content" style="">
                <div class="modal-header">
                    <h3 class="modal-title" style="color: red;font-size: 20px">警告</h3>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>请确认是否删除</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-danger" onclick="deleteProduct()">删除</button>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<script>
    //删除提示框法一
    const alterDom = document.getElementById("liveAlertPlaceholder")
    const alert = (message, type) => {
        const wrapper = document.createElement('div')
        wrapper.innerHTML = [
            `<div class="alert alert-${type} alert-dismissible" role="alert">`,
            `   <div>${message}</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('')

        alterDom.append(wrapper)
    }
    var deleteId;
    // 模态框：提示是否删除
    var myModal = new bootstrap.Modal(document.getElementById('deleteModal'), {
        keyboard: false        // 按 ESC 不能关闭
    });//模态框
    function showModal(productId) {
        myModal.show()//打开模态框
        deleteId = productId;
    }

    function deleteProduct() {
        //     浏览器的直接访问方式：Get请求
        //     发起请求方式：1：浏览器直接访问 ；2：通过访问工具来发起请求
        //     script通过浏览器发起请求方式是：window.location.href
        // 1. 立即关掉模态框
        myModal.hide();

        //访问方式一：浏览器直接访问
        // window.location.href = "/deleteProduct?id=" + deleteId;
        // 访问方式二：使用ajax访问

        // 获取 CSRF token 和 header name
        const csrfToken = $('meta[name="_csrf"]').attr('content');
        const csrfHeader = $('meta[name="_csrf_header"]').attr('content');
        // 设置 AJAX 全局默认请求头（推荐）
        $.ajaxSetup({
            beforeSend: function(xhr) {
                if (csrfToken && csrfHeader) {
                    xhr.setRequestHeader(csrfHeader, csrfToken);
                }
            }
        });

        $.ajax({
            type: 'DELETE',//访问类型：DELETE, POST, GET, PUT
            url: '/admin/deleteProduct1',//访问路径
            data: {id: deleteId,},//url请求参数:参数名:变量参数
            success: function (resp) {
                if (resp == "OK") {
                    alert("删除成功", "success");
                    setTimeout(() => {
                        // console.log(resp);//测试使用，可不写
                        location.reload();   // 重新加载 当前页面，列表就少了被删那一行，当不刷新时控制台会显示全部代码文件
                        //     或者：重新访问：window.location.href = "/getProductTable"
                    }, 500);
                }
            },
            error: function () {
            }
        });
    }
</script>
</html>
